Course Home | Lab Home | Lab Resources


CSCE 206 Labs: Commenting and Indentation Guidelines


Indentation and Comments are a vital part of writing good code. While both of these do not affect the output of the code, they will play large dividends in being able to understand and maintain your code.

Note: Code that is not properly commented and indented will lose points.


1. Commenting

There are two ways of placing comments in C/C++, use of a // and use of a /* */ block.

		//This is a single line comment

		/* This is a block/multiline comment,
		Comments that are inside the /*   */ block
		will not be executed.
		*/
	

Rule of thumb:
Someone who has not seen the assignment question, should be able to clearly understand what the program is meant to do, and how it does it.

Minimum Commenting Requirements

Do not write comments for statements that are obvious.

		//example of a bad comment
		i=i+1; // Increment i by 1.

		//example of a good comment
		value_D=pow(b,2)-4*a*c; // Discriminant (D) of a quadratic equation = b^2 - 4*a*c, 
		...			// used to identify if the roots are real or imaginary
	

Suggested reading


2. Indenting

There are many styles of Indentation. Here are two popular styles of indentations. Please pick one and stick with it throughout the course.

Type-1 : One True Brace Style (1TBS) also known as Linux Style Brackets. In this style, opening braces are on the same line as the conditional statment that it controls. (Notice the opening brace on the same line as the if and else). "Else" statments are listed on the same line as the corresponding "if", and the closing brace is at the same level of indentation as the statement that opened it.

int type1() 
{
    statement_1;
    statement_2;
    
    if (something==x) {

        statement_3;
        statement_4;

    } else {
            
        if (xNeverHappened){

            statement_8;
            statement_9;
        }

        statment_6;
        statement_7;
    }

    statement_10;
}
	

Type 2: The ANSI Style or Allman style or (bsd in Emacs). "The style puts the brace associated with a control statement on the next line, indented to the same level as the control statement. Statements within the braces are indented to the next level."

void type2() 
{
    statement_1;
    statement_2;
    
    if (something==x)
    {
        statement_3;
        statement_4;

    } 
    else 
    {
        if (xNeverHappened)
        {
            statement_8;
            statement_9;
        }
        statment_6;
        statement_7;
    }
    statement_10;
}
	

Lots more information about types of indentation styles is available on Wikipedia here.


Page reference